<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\service\BannerCategoryService;
use app\admin\service\BannerService;
use app\admin\service\DesignerService;
use think\facade\Response;
use think\facade\View;
use think\facade\Log;

class Designer extends Diluma
{
    /**
     * 首页
     * @return view
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 列表数据
     * @return json
     */
    public function getDataList(){
        $pageSize = (int)$this->request->param('page_size', 10);

        $service = new DesignerService();
        $list = $service->getDataList($pageSize);

        return json(['code'=>0, 'count'=>$list->total(), 'data'=>$list->items()]);
    }

    /**
     * 添加
     * @return mixed|Json
     * */
    public function insert(){
        if ($this->request->isPost()) {
            $service = new DesignerService();
            $post = $this->request->post(['field']);
            $data = [
                'name' => $post['field']['name'],
                'image_url' => $post['field']['image_url'],
                'position' => $post['field']['position'],
                'year' => $post['field']['year'],
                'tag' => $post['field']['tag'],
                'idea' => $post['field']['idea'],
                'desc' => $post['field']['desc'],
                'create_time' => time(),
            ];
            return $service->updateOrInsert($data);
        } else{
            return View::fetch();
        }
    }

    /**
     * 编辑
     * @return string|\think\response\Json
     */
    public function edit()
    {
        $id = $this->request->param('id');
        $service = new DesignerService();
        $item = $service->getOne($id);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if(empty($post['field']['id']) || empty($post['field']['image_url'])){
                return json(['code'=>1, 'msg'=>'参数异常']);
            }
            return $service->updateOrInsert($post['field']);
        } else{
            View::assign('item', $item);
            return View::fetch();
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }
        try {
            $service = new DesignerService();
            $service->delete($id);
            return json(['code'=>0, 'msg'=>'删除成功']);
        } catch (\Exception $e) {
            Log::error('delete error:'. $e->getMessage());
            return json(['code'=>1, 'msg'=>$e->getMessage()]);
        }
    }
}